using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
using DG.Tweening;
using Text = TMPro.TMP_Text;

public class BattleFlowController : MonoSingleton<BattleFlowController> {
	private class FoodPickMRAdapter : SimpleLayout.Adapter {
		public override int count => PlayerProp.Instance == null ? 0 : PlayerProp.Instance.mushroomCnt;
		public override void OnRender(int position, SimpleLayout.ViewCache viewCache) {
		}
	}
	private class FoodConsumeAdapter : SimpleLayout.Adapter {
		public override int count => Instance.m_curLevelInfo == null ? 0 : Instance.m_curLevelInfo.MRConsume;
		public override void OnRender(int position, SimpleLayout.ViewCache viewCache) {
		}
	}
	public enum GamePhase {
		BATTLE, PRE_BATTLE_END, FOOD_PICK, SHOP
	}

	public AutoLoader levelLoader;
	public AutoLoader rootLoader;
	public AutoLoader iconLoader;
	public Transform levelContainer;
	public GamePhase phase;
	public int levelIndex;

	public GameObject foodPickPanel;
	public SimpleLayout foodPickMRLayout;
	public SimpleLayout foodConsumeLayout;
	public GameObject noFoodTipObj;
	public GameObject hasFoodSummary;
	public GameObject noFoodSummary;
	public Text dayXText;
	public Text frontDayText;

	private Grid m_grid;
	private GameObject m_levelObj;
	private LevelInfo m_curLevelInfo;
	private int m_dayCounter = 1;
	private bool m_hasFoodNow;

	public void Start() {
		levelIndex = 0;
		LoadLevel(levelIndex);
		foodPickMRLayout.SetAdapter(new FoodPickMRAdapter());
		foodConsumeLayout.SetAdapter(new FoodConsumeAdapter());
	}

	private void Update() {
		if (Input.GetKeyDown(KeyCode.R)) {
			LoadLevel(levelIndex);
		}
		if (Input.GetKeyUp(KeyCode.Return)) {
			if (phase == GamePhase.FOOD_PICK) {
				OnPlayerConfirmFoodPick();
			}
		}
	}

	private void RestartGame() {
		levelIndex = 0;
		m_dayCounter = 1;
		LoadLevel(levelIndex);
		PlayerProp.Instance.OnReloadGame();
	}

	public void LoadLevel(int index) {
		frontDayText.text = $"Day {m_dayCounter}   -{m_dayCounter}00m";
		LoadLevel(index.ToString());
	}

	public void LoadLevel(string index) {
		if (m_levelObj != null) {
			Destroy(m_levelObj);
		}
		if (index.isNullOrEmpty()) {
			return;
		}
		var name = $"level_{index}";
		var prefab = levelLoader.Load<GameObject>(name);
		m_levelObj = Instantiate(prefab, levelContainer.transform);
		m_grid = m_levelObj.GetComponentInChildren<Grid>();
		var tileMap = m_levelObj.GetComponentInChildren<Tilemap>();
		var levelInfo = m_levelObj.GetComponent<LevelInfo>();
		m_curLevelInfo = levelInfo;
		TilemapDataManager.Instance.LoadMap(tileMap, levelInfo.size);

		var spawn = GridEntity.gridEntities.Find(x => x.entityTag == "spawn");
		var playerPrefab = rootLoader.Load<GameObject>("player");
		var player = Instantiate(playerPrefab, spawn.transform.position, spawn.transform.rotation, m_grid.transform);
	}

	public Vector3Int WorldToCell(Vector3 worldPos) {
		if (m_grid == null) {
			return Vector3Int.zero;
		}
		return m_grid.WorldToCell(worldPos);
	}

	public void GotoPhase(GamePhase phase) {
		if (this.phase == phase) {
			return;
		}
		this.phase = phase;

		foodPickPanel.SetActive(phase == GamePhase.FOOD_PICK);

		if (phase == GamePhase.FOOD_PICK) {
			var consume = m_curLevelInfo.MRConsume;
			m_hasFoodNow = PlayerProp.Instance.mushroomCnt > 0;
			PlayerProp.Instance.mushroomCnt -= consume;
			PlayerProp.Instance.mushroomCnt = Mathf.Max(0, PlayerProp.Instance.mushroomCnt);
			dayXText.text = $"Day {m_dayCounter++} ,";
			foodConsumeLayout.NotifyUpdate();
			foodPickMRLayout.NotifyUpdate();
			noFoodTipObj.SetActive(PlayerProp.Instance.mushroomCnt <= 0);
			hasFoodSummary.SetActive(m_hasFoodNow);
			noFoodSummary.SetActive(!m_hasFoodNow);
		}

		if (phase == GamePhase.PRE_BATTLE_END) {
			var seq = DOTween.Sequence();
			seq.AppendInterval(0.5f);
			seq.AppendCallback(() => {
				LoadLevel(null);
				if (phase == GamePhase.PRE_BATTLE_END) {
					GotoPhase(GamePhase.FOOD_PICK);
				}
			});
		}

		if (phase == GamePhase.BATTLE) {
			levelIndex++;
			PlayerProp.Instance.RefillEndurance();
			LoadLevel(levelIndex);
		}
	}

	public void OnPlayerEnterWhiteDoor() {
		if (phase == GamePhase.BATTLE) {
			GotoPhase(GamePhase.PRE_BATTLE_END);
		}
	}

	public void OnPlayerConfirmFoodPick() {
		if (phase == GamePhase.FOOD_PICK) {
			if (m_hasFoodNow) {
				GotoPhase(GamePhase.BATTLE);
			} else {
				RestartGame();
				GotoPhase(GamePhase.BATTLE);
			}
		}
	}

	public void AttackPlayer(int dmg) {
		if (phase != GamePhase.BATTLE) {
			return;
		}

		PlayerProp.Instance.hp--;
		PlayerEntity.Instance.ShakeVisual();
		UIPlayerPanel.Instance.ShakeHp();

		if (PlayerProp.Instance.hp == 0) {
			PlayerProp.Instance.food = 0;
			GotoPhase(GamePhase.PRE_BATTLE_END);
		}
	}

	public Sprite LoadIcon(string id) {
		var icon = iconLoader.Load<Sprite>(id);
		if (icon == null) {
			icon = iconLoader.Load<Sprite>("sprite_white");
		}
		return icon;
	}
}
